<template>
  <div>
    <el-form label-width="100px"  :model="skuInfo">
      <el-form-item label="SPU名称"> {{ spu.spuName }} </el-form-item>

      <el-form-item label="SKU名称">
        <el-input placeholder="SKU名称" v-model="skuInfo.skuName"></el-input>
      </el-form-item>

      <el-form-item label="价格(元)">
        <el-input placeholder="价格(元)" type="number" v-model="skuInfo.price"></el-input>
      </el-form-item>

      <el-form-item label="重量(千克)">
        <el-input placeholder="重量(千克)" type="number"  v-model="skuInfo.weight"></el-input>
      </el-form-item>

      <el-form-item label="规格描述">
        <el-input placeholder="规格描述" type="textarea" rows="4" v-model="skuInfo.skuDesc"></el-input>
      </el-form-item>

      <el-form-item label="平台属性">
        <el-form :inline="true" label-width="100px">
          <el-form-item
            :label="attr.attrName"
            v-for="(attr, index) in attrList"
            :key="attr.id"
          >
            <el-select  v-model="attr.attrIdValueId" placeholder="请选择">
              <el-option
                :label="attrValue.valueName"
                :value="`${attr.id}:${attrValue.id}`"
                v-for="(attrValue, index) in attr.attrValueList"
                :key="attrValue.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-form :inline="true" label-width="100px">
          <el-form-item
            :label="saleAttr.saleAttrName"
            v-for="(saleAttr, index) in spuSaleAttrList"
            :key="saleAttr.id"
          >
            <el-select v-model="saleAttr.saleAttrIdValueId" placeholder="请选择">
              <el-option
                :label="saleAttrValue.saleAttrValueName"
                :value="`${saleAttr.id}:${saleAttrValue.id}`"
                v-for="(saleAttrValue, index) in saleAttr.spuSaleAttrValueList"
                :key="saleAttrValue.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="图片列表">
        <el-table border style="width: 100%" :data="spuImageList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="图片" width="width">
            <template slot-scope="{ row, $index }">
              <img
                :src="row.imgUrl"
                alt="x"
                style="width: 100px; height: 100px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称" width="width">
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
                <!-- 排它处理设置默认图片 -->
              <el-button  @click="changeDefault(spuImageList,row)" v-if="row.isDefault === '0' "  type="primary" size="mini">设为默认</el-button>
              <el-tag  v-else  type="success">默认</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancleBack" 
          >取消</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SkuFrom",
  data() { 
    return {
      spu: {},
      attrList: [], //三级联动数据
      spuSaleAttrList: [], //spu销售属性列表
      spuImageList: [], //spu图片列表 //这个列表是spu所有的图片列表，展示出来是为了让用户选择的，不能去收集选中的sku图片
      skuImageList:[], //自己写一个专门用来收集选中的sku图片列表，后期保存的时候整理完成再去放到skuInfo里面


      skuInfo: {
        //父组件传递过来的
        category3Id: 0,
        spuId: 0,
        tmId: 0,

        //通过v-model直接收集的
        skuDesc: "",
        skuName: "",
        weight: "",
        price: '',

        //通过代码去完成收集的 
        skuDefaultImg: "", //收集默认图片
        skuAttrValueList: [
        //   {
        //     attrId: 0,
        //     attrName: "string",
        //     id: 0,
        //     skuId: 0,
        //     valueId: 0,
        //     valueName: "string",
        //   },
        ],

        skuImageList: [
        //   {
        //     id: 0,
        //     imgName: "string",
        //     imgUrl: "string",
        //     isDefault: "string",
        //     skuId: 0,
        //     spuImgId: 0,
        //   },
        ],

        skuSaleAttrValueList: [ 
        //   {
        //     id: 0,
        //     saleAttrId: 0,
        //     saleAttrName: "string",
        //     saleAttrValueId: 0,
        //     saleAttrValueName: "string",
        //     skuId: 0,
        //     spuId: 0,
        //   },
        ],
      },
    };
  },
  methods: {
    async getInitAddSkuFromData(row, category1Id, category2Id, category3Id) {
      // http://localhost:9529/dev-api/admin/product/attrInfoList/2/13/61
      this.spu = row;
      let promise1 = this.$API.attr.getList(
        category1Id,
        category2Id,
        category3Id
      );

      // http://localhost:9529/dev-api/admin/product/spuSaleAttrList/6
      let promise2 = this.$API.sku.getSpuSaleAttrList(this.spu.id);

      // http://localhost:9529/dev-api/admin/product/spuImageList/6
      let promise3 = this.$API.sku.getSpuImageList(this.spu.id);

      try {
        const result = await Promise.all([promise1, promise2, promise3]);
        this.attrList = result[0].data;
        this.spuSaleAttrList = result[1].data;

        let spuImageList = result[2].data; //每一项图片都加一个isDefault
        spuImageList.forEach(item=>item.isDefault = '0')
        this.spuImageList =  spuImageList
        
        
      } catch (error) {
        this.$message.error("获取初始化数据失败" + error.messsage);
      }
    },

    //多选框改变选择处理函数
    handleSelectionChange(val) {
        // console.log(val);//val代表选中的图片
        this.skuImageList = val
      },

    //选中图片的回调
    changeDefault(spuImageList,row){
        spuImageList.forEach(item=>item.isDefault = '0')
        row.isDefault = '1'
        this.skuInfo.skuDefaultImg = row.imgUrl//收集默认图片的路径

    },

    //点击'保存'，收集数据发请求
    async save(){
        //获取请求参数 //spu  attrList spuSaleAttrList skuImageList skuInfo
        let {spu,attrList,spuSaleAttrList,skuImageList,skuInfo} = this
        //整理参数
            //先整理spu内部的，父组件传递的
            skuInfo.category3Id = spu.category3Id
            skuInfo.spuId = spu.id
            skuInfo.tmId = spu.tmId
            //整理sku的图片列表
                   // {//这是我们需要整理的参数
                    //     imgName: "string",
                    //     imgUrl: "string",
                    //     isDefault: "string",
                    //     spuImgId: 0,
                    // },
                //   {//我们目前已有的数据
                //         id:27
                //         imgName:"0e99152a7e59c478.jpg"
                //         imgUrl:"http://47.93.148.192:8080/group1/M00/02/DA/rBHu8mGxO7mAJ8keAACU-49r2kw775.jpg"
                //         isDefault:"0"
                //         spuId:5
                //   }

            skuInfo.skuImageList  = skuImageList.map(item=>({
                      imgName:item.imgName,
                       imgUrl:item.imgUrl,
                       isDefault:item.isDefault,
                       spuImgId:item.id,
            }))
            //整理sku的平台属性值列表和销售属性值列表
                //我们之前在attrList添加了两个id拼接的串，代表我们选中的属性和属性值，现在要找出来放在
                //新的skuInfo.skuAttrValueList中
            skuInfo.skuAttrValueList = attrList.reduce((prev,item)=>{
                    if(item.attrIdValueId){
                        let [attrId,valueId] = item.attrIdValueId.split(':')
                        let obj = {attrId,valueId}
                        prev.push(obj)
                    }
                    return  prev
            },[])

            skuInfo.skuSaleAttrValueList = spuSaleAttrList.reduce((prev,item)=>{
                if(item.saleAttrIdValueId){//${saleAttr.id}:${saleAttrValue.id}
                    //saleAttrId  saleAttrValueId
                    let [saleAttrId,saleAttrValueId] = item.saleAttrIdValueId.split(':')
                    let obj = {saleAttrId,saleAttrValueId}
                    prev.push(obj)
                }
                return prev
            },[])

        //发请求
        try {
            //成功干啥
            const result = await this.$API.sku.addUpdate(skuInfo)
            if(result.code === 200 || result.code === 20000){
                    this.$message.success('保存sku成功')
                    this.$emit('update:isShowSkuFrom',false)
                     //不需要重新让父组件发请求获取spu的列表数据，因为spu列表并没有改变
                     this.resetData()
            }else{
                this.$message.error('保存sku失败')
            }
        } catch (error) {
                //失败干啥
                this.$message.error('请求保存sku失败')
        }
    },

    //清空data的所有数据
    resetData(){
        Object.assign(this._data,this.$options.data())
    },

    //点击'取消' 
     cancleBack(){
          this.$emit('update:isShowSkuFrom', false)
          this.resetData()
     }
  },
};
</script>

<style>
</style>